java中缀到后缀未按预期工作
我在Java中有一个家庭作业,我必须将不带括号的中缀字符串转换为后缀字符串。两天来我一直在修补代码,但一直没能发现bug。这是我的密码
public class itp
{
String exp, post;
double res;
int l;
stack st;
public itp(String s)
{
exp = s;
post = "";
l = exp.length();
st = new stack(l);
conv();
calc();
System.out.println("The postfix notation of "+exp+" is "+post);
System.out.println("The result of "+exp+" is "+res);
}
public void conv()
{
char ch = ' ';
char pre = ' ';
for(int i =0;i<l;i++)
{
ch = exp.charAt(i);
if("+-*/".indexOf(ch)==-1)post = post + ch;
else
{
pre = st.pop();
if(val(ch)>=val(pre))
{
st.push(pre);
st.push(ch);
}
else
{
while((val(ch)<=val(pre))&&(pre!='$'))
{
post = post + pre;
pre = st.pop();
}
st.push(ch);
}
}
}
for(pre = st.pop();pre!='$';pre = st.pop())
{
post = post + pre;
}
}
public void calc()
{
res = 0.0;
}
public int val(char c)
{
switch(c)
{
case '$' : return 0;
case '+' : return 1;
case '-' : return 2;
case '*' : return 3;
case '/' : return 4;
default : return -1;
}
}
}
在此,变量如下所示:
st
是一个字符堆栈ch
是当前字符pre
是堆栈上最上面的字符exp
是输入中缀表达式post
是输出后缀表达式
pop()方法按预期工作,除非堆栈为空,否则它将返回$
。函数val()接受字符输入,并为/
返回4,为*
返回3。2代表-
。1代表+
。整数l
包含exp
的长度
它在大多数情况下都能很好地工作,除非我给它一个类似a*b-b*c+c*d-d*e
的字符串,其中它输出ab*bc*-cd*de*-
,这是预期的输出,最后没有+
任何建议都将不胜感激。这只虫子快把我逼疯了
以下是完整的代码:
public class itp
{
String exp, post;
double res;
int l;
stack st;
public itp(String s)
{
exp = s;
post = "";
l = exp.length();
st = new stack(l);
conv();
calc();
System.out.println("The postfix notation of "+exp+" is "+post);
System.out.println("The result of "+exp+" is "+res);
}
public void conv()
{
char ch = ' ';
char pre = ' ';
for(int i =0;i<l;i++)
{
ch = exp.charAt(i);
if("+-*/".indexOf(ch)==-1)post = post + ch;
else
{
pre = st.pop();
if(val(ch)>=val(pre))
{
st.push(pre);
st.push(ch);
}
else
{
while((val(ch)<=val(pre))&&(pre!='$'))
{
post = post + pre;
pre = st.pop();
}
st.push(ch);
}
}
}
for(pre = st.pop();pre!='$';pre = st.pop())
{
post = post + pre;
}
}
public void calc()
{
res = 0.0;
}
public int val(char c)
{
switch(c)
{
case '$' : return 0;
case '+' : return 1;
case '-' : return 2;
case '*' : return 3;
case '/' : return 4;
default : return -1;
}
}
}
下面是stack类:
public class stack
{
char[] a;
int top,size;
public stack(int s)
{
size = s;
a = new char[size];
top = -1;
}
public void push(char el)
{
a[++top] = el;
}
public char pop()
{
if(empty()) return '$';
else return a[top--];
}
public boolean empty()
{
return (top == -1);
}
}
这是主要课程
import java.util.Scanner;
class client
{
public static void main(String args[])
{
System.out.println("Enter the expression");
Scanner in = new Scanner(System.in);
itp i = new itp(in.next());
}
}
# 1 楼答案
首先
a*b-b*c+c*d-d*e
的后修复不是ab*bc*-cd*de*-+
,而是ab*bc*-cd*+de*-
第二个错误是在
val()
函数中。它应该是:换一下,检查一下。这肯定会奏效